package org.oms.avatar.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.oms.avatar.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.sina.sae.storage.SaeStorage;
import com.sina.sae.util.SaeUserInfo;

/**
 * Handles requests for the application Upload page.
 */
@Controller
public class SinaController {

	private static final Logger logger = LoggerFactory.getLogger(SinaController.class);
	private static final String filePath="D:\\";
	

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/sina", method = RequestMethod.GET)
	public String avatar(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		model.addAttribute("serverTime", new Date());
		return "sina_upload";
	}

	@RequestMapping(value = "/upload2sina",method=RequestMethod.POST)
	public void upload(HttpServletRequest request,HttpServletResponse response) throws FileUploadException, IOException {
		String contentType = request.getContentType();
		// 使用SaeUserInfo拿到此请求可写的路径
		String realPath = SaeUserInfo.getSaeTmpPath() + "/";
		PrintWriter out = response.getWriter();
		if (contentType.indexOf("multipart/form-data") >= 0) {
			Result result = new Result();
			result.avatarUrls = new ArrayList();
			result.success = false;
			result.msg = "Failure!";

			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			FileItemIterator fileItems = null;
			try {
				fileItems = upload.getItemIterator(request);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			// 定义一个变量用以储存当前头像的序号
			// 取服务器时间+8位随机码作为部分文件名，确保文件名无重复。
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
			String fileName = simpleDateFormat.format(new Date());
			// 基于原图的初始化参数
			String initParams = "";
			BufferedInputStream inputStream;
			BufferedOutputStream outputStream;
			// 遍历表单域
			while (fileItems.hasNext()) {
				FileItemStream fileItem = fileItems.next();
				String fieldName = fileItem.getFieldName();
				// 是否是原始图片 file 域的名称（默认的 file
				// 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）
				Boolean isSourcePic = fieldName.equals("__source");
				// 当前头像基于原图的初始化参数（只有上传原图时才会发送该数据，且发送的方式为POST），用于修改头像时保证界面的视图跟保存头像时一致，提升用户体验度。
				// 修改头像时设置默认加载的原图url为当前原图url+该参数即可，可直接附加到原图url中储存，不影响图片呈现。
				if (fieldName.equals("__initParams")) {
					inputStream = new BufferedInputStream(fileItem.openStream());
					byte[] bytes = new byte[inputStream.available()];
					inputStream.read(bytes);
					initParams = new String(bytes, "UTF-8");
					inputStream.close();
				}
				// 如果是原始图片 file
				// 域的名称或者以默认的头像域名称的部分“__avatar”打头(默认的头像域名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names)
				else if (isSourcePic || fieldName.startsWith("__avatar")) {
					String virtualPath = "/upload/img_face_" + fileName + ".jpg";
					// 原始图片（默认的 file
					// 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）。
					if (isSourcePic) {
						// 文件名，如果是本地或网络图片为原始文件名（不含扩展名）、如果是摄像头拍照则为 *FromWebcam
						// fileName = fileItem.getName();
						result.sourceUrl = virtualPath = "/upload/img_source_" + fileName + ".jpg";
					}
					// 头像图片（默认的 file
					// 域的名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names）。
					else {
						result.avatarUrls.add(virtualPath);
					}
					inputStream = new BufferedInputStream(fileItem.openStream());
					//outputStream = new BufferedOutputStream(new FileOutputStream(filePath + virtualPath.replace("/", "\\")));
					outputStream = new BufferedOutputStream(new FileOutputStream("saestor://omstemplate.sinaapp.com" + virtualPath));
					Streams.copy(inputStream, outputStream, true);
					// 上传完毕后 使用SaeStorage往storage里面写
					SaeStorage saeStorage = new SaeStorage();
					// 使用upload方法上传到域为image下
					saeStorage.upload("upload", realPath + virtualPath, fileItem.getName());
					saeStorage.getUrl("upload", fileItem.getName());
					inputStream.close();
					outputStream.flush();
					outputStream.close();
				} else {
					// 注释①
					// upload_url中传递的查询参数，如果定义的method为post请使用下面的代码，否则请删除或注释下面的代码块并使用注释②的代码
					inputStream = new BufferedInputStream(fileItem.openStream());
					byte[] bytes = new byte[inputStream.available()];
					inputStream.read(bytes);
					inputStream.close();
					if (fieldName.equals("userid")) {
						result.userid = new String(bytes, "UTF-8");
					} else if (fieldName.equals("username")) {
						result.username = new String(bytes, "UTF-8");
					}
				}
			}
			if (result.sourceUrl != null) {
				result.sourceUrl += initParams;
			}
			result.success = true;
			result.msg = "Success!";
			// 返回图片的保存结果（返回内容为json字符串，可自行构造，该处使用fastjson构造）
			out.println(JSON.toJSONString(result));
		}
		out.close();
	}
	
}
